package com.superatom.concurrent.share;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 本demo介绍的是使用ReentrantLock，
 * 它的tryLock()允许你尝试获取但最终未获取锁，
 * 其实带有lock()的功能，就是有机会获得锁。
 */
public class AttemptLocking {

    private ReentrantLock lock = new ReentrantLock();

    /**
     * 尝试获得锁，如果别人已经获取的这个锁，线程就可以离开做某些事情，而不是等待直到锁释放
     */
    public void untimed() {
        boolean captured = lock.tryLock();
        try{
            System.out.println("tryLock(): " + captured);
        }finally {
            if (captured){
                lock.unlock();
            }
        }
    }

    /**
     * 尝试获得锁，如果两秒后获取不了，宣布失败
     */
    public void timed() {
        boolean captured = false;
        try {
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try{
            System.out.println("tryLock(2, TimeUnit.SECONDS): " + captured);
        }finally {
            if (captured){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final AttemptLocking al = new AttemptLocking();
        al.untimed();
        al.timed();

        new Thread(){
            {
                this.setDaemon(true);
            }

            @Override
            public void run() {
                al.lock.lock();
                System.out.println("acquired");
            }
        }.start();

        Thread.sleep(100);

        al.untimed();
        al.timed();
    }
}
